package com.app.couponsharelife.ui.main.me.profit.record
import android.graphics.Color
import android.graphics.drawable.AnimationDrawable
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bigkoo.pickerview.builder.TimePickerBuilder
import com.bigkoo.pickerview.listener.OnTimeSelectListener
import com.bigkoo.pickerview.view.TimePickerView
import com.gavin.com.library.PowerfulStickyDecoration
import com.gavin.com.library.listener.PowerGroupListener
import com.makeramen.roundedimageview.RoundedImageView
import com.app.couponsharelife.R
import com.app.couponsharelife.base.BaseActivity
import com.app.couponsharelife.data.bean.EarningsRecord
import com.app.couponsharelife.data.bean.RemoteResultBean
import com.app.couponsharelife.data.bean.UserEarningsBean
import com.app.couponsharelife.data.remote.retrofit.RetrofitWorker
import com.app.couponsharelife.data.remote.retrofit.exception.OtherException
import com.app.couponsharelife.manage.Contacts
import com.app.couponsharelife.ui.listener.MyMultiPurposeListener
import com.app.couponsharelife.utils.AppUtils
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.observers.DisposableObserver
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_not_profit_record.*
import kotlinx.android.synthetic.main.base_refresh_head.*
import kotlinx.android.synthetic.main.base_title_white.*
import kotlinx.android.synthetic.main.pickerview_time_selecte.view.*
import kotlinx.android.synthetic.main.profit_list_rvtop.view.*
import kotlinx.android.synthetic.main.profit_record_item.view.*
import java.text.SimpleDateFormat
import java.util.*

/**
 *Created by xct on 2019/5/13
 *Description:未结算收益明细
 */
class NotProfitRecordActivity:BaseActivity() {
    private var pvTime: TimePickerView? = null
    private var pageIndex=1
    private var time=""
    private var dataList= arrayListOf<EarningsRecord>()
    private var adapter:MyAdapter?=null
    private var decoration:PowerfulStickyDecoration?=null
    private val simpleDateFormat = SimpleDateFormat("yyyy-MM", Locale.getDefault())
    override val viewLayoutId: Int
        get() = R.layout.activity_not_profit_record

    override fun initViews() {
        AppUtils.initImmersionBar(this,true)
        basetitle_title.text="待结算明细"
        basetitle_llRight.visibility=View.VISIBLE
        setRefresh()
        adapter=MyAdapter()
        notProfit_rv.layoutManager= LinearLayoutManager(this)
        val listener=object : PowerGroupListener {
            override fun getGroupName(position: Int): String {
                return dataList[position].headTime
            }
            override fun getGroupView(position: Int): View {
                val view=LayoutInflater.from(this@NotProfitRecordActivity).inflate(R.layout.profit_list_rvtop, null, false)
                view.profitList_tvTime.text=dataList[position].headTime
                //Log.e("eeee","---->"+dataList[position].createTime)
                view.profitList_tvPrice.text="预估收益 ¥"+dataList[position].totalMoney
                return view
            }
        }
        decoration= PowerfulStickyDecoration.Builder.init(listener)
                .setGroupBackground(resources.getColor(R.color.gray_f3f4))
                .build()
        notProfit_rv.addItemDecoration(decoration!!)
        notProfit_rv.adapter=adapter
        notProfit_butTime.setOnClickListener {
            timePickers()
        }
        basetitle_llclose.setOnClickListener { finish() }
        basetitle_llRight.setOnClickListener {
            timePickers()
        }
        getData(false)
    }
    private fun setRefresh(){
        hotsale_refreshimg.setImageResource(R.drawable.anim_refresh)
        val animationDrawable=hotsale_refreshimg.drawable as AnimationDrawable
        notProfit_smartrefresh.setOnMultiPurposeListener(object : MyMultiPurposeListener {
            override fun headerReleased() {
                animationDrawable.start()
            }

            override fun headerMoving(percent: Float) {
                setAnima(percent)
            }

            override fun headerFinish() {
                hotsale_refreshimg.setImageResource(R.drawable.refresh_0)
                animationDrawable.stop()
            }

            override fun loadMore() {
                getData(false)
            }

            override fun refresh() {
                pageIndex=1
                getData(true)
            }
        })
    }
    private fun setAnima(vlaue:Float){
        val layoutParams=hotsale_refreshimg.layoutParams as ConstraintLayout.LayoutParams
        layoutParams.matchConstraintPercentHeight=vlaue/2
        layoutParams.dimensionRatio="0.875:1"
        hotsale_refreshimg.layoutParams=layoutParams
    }
    fun timePickers() {
        time=simpleDateFormat.format(System.currentTimeMillis())
        val selectedDate = Calendar.getInstance()
        val startDate = Calendar.getInstance()
        val endDate = Calendar.getInstance()
        startDate.set(2016, 0, 1)
        endDate.set(2030, 11, 31)
        pvTime = TimePickerBuilder(this, OnTimeSelectListener { _, _ ->

        })
                .setDate(selectedDate)
                .setRangDate(startDate, endDate)
                .setLayoutRes(R.layout.pickerview_time_selecte) { v ->
                    v.pickerview_tvQX.setOnClickListener { pvTime!!.dismiss() }
                    v.pickerview_tvWC.setOnClickListener{
                        pageIndex=1
                        getData(false)
                        pvTime!!.dismiss()
                    }
                }.setTimeSelectChangeListener { date ->
                    time=simpleDateFormat.format(date.time)
                }
                .isCyclic(true)
                .setType(booleanArrayOf(true, true, false, false, false, false))
                .setLabel("年", "月", null, null, null, null)
                .setOutSideCancelable(true)  //点击外部区域关闭窗口
                //.setTextXOffset(-20, 0, 20, 0, 0, 0)
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setDividerColor(Color.parseColor("#e2e1e1"))
                .isDialog(false)
                .setBackgroundId(Color.parseColor("#40333333"))
                .build()
        pvTime!!.show()
    }
    private fun getData(isRefresh:Boolean){
        if (pageIndex==1){
            showProgressDialog("加载中...")
        }
        val map= HashMap<String,String>()
        map["pageNo"]=pageIndex.toString()
        map["pageSize"]="10"
        map["userId"]=AppUtils.getString(Contacts.USERID, "")
        map["time"]=time
        RetrofitWorker.retrofitWorker.getForecastEarnings(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : DisposableObserver<RemoteResultBean<UserEarningsBean>>(){
                    override fun onComplete() {

                    }

                    override fun onNext(it: RemoteResultBean<UserEarningsBean>) {
                        if (pageIndex==1){
                            dismissProgressDialog()
                            dataList.clear()
                        }
                        if (it.code==200){
                            if (it.data!!.records!=null&&it.data!!.records!!.isNotEmpty()){
                                if (pageIndex==1){
                                    notProfit_llnodata.visibility= View.GONE
                                    notProfit_rv.visibility= View.VISIBLE
                                    if (isRefresh){
                                        notProfit_smartrefresh.finishRefresh()
                                    }
                                }else{
                                    notProfit_smartrefresh.finishLoadMore()
                                }
                                setData(it.data!!.records!!)
                                /*if (dataList.size>=it.data!!.total.toInt()){
                                    onlineProfit_smartrefresh.finishLoadMoreWithNoMoreData()
                                }*/
                                pageIndex++
                                adapter!!.notifyDataSetChanged()
                                decoration!!.clearCache()
                            }else{
                                if (pageIndex==1&&dataList.size==0){
                                    notProfit_smartrefresh.finishRefresh()
                                    notProfit_llnodata.visibility= View.VISIBLE
                                    notProfit_errormsg.text="您还没有收益记录哦"
                                    notProfit_butTime.visibility= View.GONE
                                    notProfit_rv.visibility= View.GONE
                                }else{
                                    showToastMsg("没有更多数据了！")
                                }
                                notProfit_smartrefresh.finishLoadMoreWithNoMoreData()
                            }
                        }
                    }

                    override fun onError(e: Throwable) {
                        if (pageIndex==1){
                            dismissProgressDialog()
                            if (isRefresh){
                                notProfit_smartrefresh.finishRefresh()
                                notProfit_smartrefresh.finishLoadMoreWithNoMoreData()
                            }
                        }
                        if (e is OtherException){
                            //showToastMsg("没有找到任何数据，换一个试试！")
                            notProfit_llnodata.visibility= View.VISIBLE
                            notProfit_errormsg.text="没有找到${time}的收益记录"
                            notProfit_butTime.visibility= View.VISIBLE
                            notProfit_rv.visibility= View.GONE
                        }else{
                            showToastMsg("网络加载出错了！")
                        }
                    }
                })
    }
    private fun setData(list:List<EarningsRecord>){
        val time=simpleDateFormat.format(System.currentTimeMillis())
        for (i in 0 until list.size){
            val datas=list[i]
            val times=datas.createTime.substring(0,7)
            datas.headTime=if (times==time){"本月"}else {times}
            dataList.add(datas)
        }
    }
    override fun onDestroy() {
        super.onDestroy()
        AppUtils.destroyImmersionBar(this)
    }
    private inner class MyAdapter: RecyclerView.Adapter<RecyclerView.ViewHolder>(){
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
            val view= LayoutInflater.from(parent.context).inflate(R.layout.profit_record_item, parent, false)
            return MyHolder(view)
        }

        override fun getItemCount(): Int {
            return dataList.size
        }

        override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
            if (dataList.size>0){
                if (holder is MyHolder){
                    val datas=dataList[position]
                    holder.tvName!!.text=datas.nickName
                    var type=""
                    if ("4"==datas.type){
                        type="分红奖励"
                    }else {
                        type = if (-1 == datas.moneytype) {
                            "结算"
                        } else {
                            "预估"
                        }
                        var type1=""
                        when(datas.type){
                            "1"->{type1=" 自购奖励"}
                            "2"->{type1=" 团队奖励"}
                            "3"->{type1=" 平级奖励"}
                            "5"->{type1=" 推荐奖励"}
                            "6"->{type1=" 0元购补贴"}
                        }
                        type += type1
                    }
                    holder.tvType!!.text=type
                    val id=when(datas.rechargetype){
                        1->{ R.drawable.goods_tb}
                        2->{ R.drawable.goods_jd}
                        3->{ R.drawable.goods_pdd}
                        4->{ R.drawable.goods_tm}
                        else->{R.drawable.goods_tb}
                    }
                    if (datas.status=="1"){
                        holder.ivOrderType!!.visibility=View.INVISIBLE
                    }else{
                        holder.ivOrderType!!.visibility=View.VISIBLE
                    }
                    holder.faceImag!!.setImageResource(id)
                    holder.tvTime!!.text=datas.createTime
                    holder.tvPrice!!.text=datas.credit2
                }

            }
        }

    }
    private inner class MyHolder(itemview: View): RecyclerView.ViewHolder(itemview){
        var tvName: TextView?=null
        var tvType: TextView?=null
        var tvOrType: TextView?=null
        var tvTime: TextView?=null
        var faceImag: RoundedImageView?=null
        var tvJia: TextView?=null
        var tvPrice: TextView?=null
        var ivOrderType: ImageView?=null
        init {
            tvName=itemview.tvNikname
            tvType=itemview.onlin_tvType
            tvOrType=itemview.onlin_tvOrType
            tvTime=itemview.onlin_tvTime
            faceImag=itemview.userimag
            tvJia=itemview.onlin_tvJia
            tvPrice=itemview.tvProfitRecordMoney
            ivOrderType=itemview.ivOrderType
        }
    }
}